package com.itheima.user.controller;

import com.github.pagehelper.Page;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.pojo.User;
import com.itheima.user.service.UserService;
import com.itheima.util.CookieUtil;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import com.netflix.client.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping
    public Result findAll(){
        List<User> userList = userService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",userList) ;
    }

    /***
     * 根据ID查询数据
     * @param phone
     * @return
     */
    @GetMapping("/{phone}")
    public Result findById(@PathVariable String phone){
        User user = userService.findById(phone);
        return new Result(true,StatusCode.OK,"查询成功",user);
    }

    /***
     * 根据ID查询数据
     * @param username
     * @return
     */
    @GetMapping("/{username}")
    public User findByUsername(@PathVariable("username") String username){
        User user = userService.findByusername(username);
        return user;
    }


    /***
     * 新增数据
     * @param user
     * @return
     */
    @PostMapping
    public Result add(@RequestBody User user){
        userService.add(user);
        return new Result(true,StatusCode.OK,"添加成功");
    }


    /***
     * 修改数据
     * @param user
     * @param phone
     * @return
     */
    @PutMapping(value="/{phone}")
    public Result update(@RequestBody User user,@PathVariable String phone){
        user.setPhone(phone);
        userService.update(user);
        return new Result(true,StatusCode.OK,"修改成功");
    }


    /***
     * 根据ID删除品牌数据
     * @param phone
     * @return
     */
    @DeleteMapping(value = "/{phone}" )
    public Result delete(@PathVariable String phone){
        userService.delete(phone);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /***
     * 多条件搜索品牌数据
     * @param searchMap
     * @return
     */
    @GetMapping(value = "/search" )
    public Result findList(@RequestParam Map searchMap){
        List<User> list = userService.findList(searchMap);
        return new Result(true,StatusCode.OK,"查询成功",list);
    }

    /***
     * 分页搜索实现
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result findPage(@RequestParam Map searchMap, @PathVariable  int page, @PathVariable  int size){
        Page<User> pageList = userService.findPage(searchMap, page, size);
        PageResult pageResult=new PageResult(pageList.getTotal(),pageList.getResult());
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }

    @RequestMapping("/toLogin")
    public String toLogin(@RequestParam(value = "FROM",required = false,defaultValue = "") String from, Model model){
        model.addAttribute("from",from);
        return "login";
    }

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     *登录
     * @param map
     * @return
     */

    @RequestMapping("/login")
    public Result login(@RequestBody Map map,HttpServletResponse response){
        //1.验证码比对
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        String codeInRedis = (String)redisTemplate.boundValueOps(phone+ RedisMessageConstant.SENDTYPE_LOGIN).get();
        if (code != null && codeInRedis != null && code.equals(codeInRedis)){
            userService.login(phone);
        }
        //生成盐
        String gensalt = BCrypt.gensalt();
        String phoneGensalt = BCrypt.hashpw(phone, gensalt);

        //存在则将user信息写入cookie
        this.saveJtiToCookie(phoneGensalt,response);
        Map<String, String> mapUser = new HashMap<>();
        mapUser.put("login",phone);
        //存在则将user信息(phone)写入redis
        redisTemplate.boundValueOps(phoneGensalt).set(mapUser,12,TimeUnit.HOURS);

        return new Result(true,StatusCode.OK,"登录成功");
    }



    //手机快速登录验证码
    @RequestMapping("/send4Login")
    public Result send4Login(@RequestBody String phone){
        if(phone==null){
             throw new RuntimeException("电话号为空");
        }
        //生成验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);

        //发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,phone,validateCode.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.OK,"发送验证码失败");
        }
        System.out.println(validateCode.toString());
        //保存验证码至redis
        redisTemplate.boundValueOps(phone+RedisMessageConstant.SENDTYPE_LOGIN).set(String.valueOf(validateCode),5, TimeUnit.MINUTES);
        return new Result(true,StatusCode.OK,"发送验证码成功");
    }


    //将令牌的断标识jti存入到cookie中
    private void saveJtiToCookie(String phone, HttpServletResponse response) {
        CookieUtil.addCookie(response,cookieDomain,"/","remark_token",phone,-1,false);
    }

}
